#加密签名和解密的封装方法

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadSignature,SignatureExpired
from rest_framework.response import Response
from mall import settings

def generic_access_token(openid):
    #配置加密签名的参数    秘钥和时间
    serializer = Serializer(settings.SECRET_KEY,3600)
    #添加加密的数据  openid 进行加密
    token = serializer.dumps({'openid':openid})
    #返回数据 应为加密后是b二进制 所以返回时不要忘记 解码
    return token.decode()

#解密  如果用户没有绑定 则需要进行绑定而绑定则需要openid 的认证  所以这时需要解码
def check_open_id(token):

    #生成解密配置
    serializer = Serializer(settings.SECRET_KEY,3600)
    #进行解密校验
    try:
        result = serializer.loads(token)
    except BadSignature:
        return None
    else:
        return result.get('openid')


def get_token(qquser):
    from rest_framework_jwt.settings import api_settings

    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    payload = jwt_payload_handler(qquser.user)
    token = jwt_encode_handler(payload)

    return Response({
        'user_id': qquser.user.id,
        'username': qquser.user.username,
        'token': token
    })
